import { defineStore } from 'pinia'

// 定义用户状态存储
export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '', // 登录令牌
    info: {
      username: '',
      role: '',
      email: '',
      bio: ''
    }, // 用户信息
    permissions: [] // 用户权限列表
  }),
  actions: {
    // 设置令牌
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
    // 清除令牌
    clearToken() {
      this.token = ''
      localStorage.removeItem('token')
    },
    // 设置用户信息
    setUserInfo(info) {
      this.info = { ...this.info, ...info }
    },
    // 设置用户权限
    setPermissions(permissions) {
      this.permissions = permissions
    },
    // 登出
    logout() {
      this.clearToken()
      this.info = { username: '', role: '', email: '', bio: '' }
      this.permissions = []
    }
  },
  getters: {
    // 是否登录
    isLoggedIn: (state) => !!state.token,
    // 是否为管理员
    isAdmin: (state) => state.info.role === 'admin' || state.permissions.includes('admin')
  }
})